class AddRightsToQuotes < ActiveRecord::Migration
  def self.create_right(name, controller, action)
    Right.create :name => name, :controller => controller, :action => action
  end
  
  def self.remove_right(controller, action)
    Right.find(:all, :conditions => "controller = '#{controller}' AND action = '#{action}'").each do |right|
      RoleRight.find(:all, :conditions => "right_id = #{right.id}").each do |role_right|
        role_right.destroy
      end
      right.destroy
    end
  end
  
  def self.up
    rights = {
      :quotes => {
        :new_document => create_right('Uusi dokumentti', 'quotes', 'new_document'),
        :create_document => create_right('Tallenna dokumentti', 'quotes', 'create_document'),
        :remove_document => create_right('Poista dokumentti', 'quotes', 'remove_document'),
        :select_resource => create_right('Valitse resurssi', 'quotes', 'select_resource'),
        :add_resource => create_right('Lisää resurssi', 'quotes', 'add_resource'),
        :remove_resource => create_right('Poista resurssi', 'quotes', 'remove_resource')
      }
    }
    roles = {:seller => Role.find_by_name('Myyjä')}
    roles[:seller].rights << rights[:quotes][:new_document]
    roles[:seller].rights << rights[:quotes][:create_document]
    roles[:seller].rights << rights[:quotes][:remove_document]
    roles[:seller].rights << rights[:quotes][:select_resource]
    roles[:seller].rights << rights[:quotes][:add_resource]
    roles[:seller].rights << rights[:quotes][:remove_resource]
  end
  
  def self.down
    remove_right('quotes', 'new_document')
    remove_right('quotes', 'create_document')
    remove_right('quotes', 'remove_document')
    remove_right('quotes', 'select_resource')
    remove_right('quotes', 'add_resource')
    remove_right('quotes', 'remove_resource')
  end
end
